const Router = require('koa-router');
const tool = require("../../tools/tool");
const router = new Router();
const {db, Op, QueryTypes} = require("../../models/db");
const tools = require("../../tools/tool");
const getUploadToken = require("qiniu");
const {exec} = require("child_process");

// 验证 验证码,终端登录
router.post('/common/validSms', async ctx => {
    let mobile = tools.xe.toString(ctx.request.body.mobile);
    let smsId = tools.xe.toString(ctx.request.body.yzm);
    let isLogin = ctx.request.body.isLogin?ctx.request.body.isLogin:false
    if(mobile && smsId) {
        let command = `curl -X POST  http://smsapi.sanzhiyun.cn/1/verifySmsCode/${smsId} -H "X-Bmob-Application-Id:6095550591df6bd5b252fad4012dcc90" -H "X-Bmob-REST-API-Key: 83e5bbe060ffd6d7e346919df019edb5" -d "{\\"mobilePhoneNumber\\": \\"${mobile}\\"}" -H "Content-Type: application/json"`
        let ret = await exeCurl1(command)
        if(ret.stat) {
            // 验证码正确
           if(isLogin) {
               return await terLogin(ctx, mobile)
           }
           else {
               return ctx.suc('')
           }
        }
        else {
            return ctx.err(ret.msg)
        }
    }
    else {
        return  ctx.err('请填写验证码'+mobile)
    }
})
const terLogin = async (ctx, mobile) => {
   try {
       // 是否在contact表中有手机号
       let hasSql = `select count(*) total from contact where disabled=0 and linkMobile='${mobile}' `
       let model = await db.query(hasSql, {type: QueryTypes.SELECT, plain: true})
       if(model.total === 0) {
           return ctx.err('还没有该手机号关联的终端')
       } else if(model.total === 1) {
           let contactModel = await db.query(`select * from contact where disabled=0 and linkMobile='${mobile}' `,{type: QueryTypes.SELECT, plain: true})
           //
           let num = await db.models['admin'].count({
               where: {
                   username: mobile
               }
           })
           if(num === 0) {
               // 查看是否有重复名称
               // 新增
               let userModel = db.models['admin'].build()
               userModel.tenantId = contactModel.tenantId
               userModel.username = contactModel.linkMobile
               userModel.userpwd = tool.crypto.MD5('s123456')
               userModel.token = tool.uuid()
               userModel.name = contactModel.linkName?contactModel.linkName:contactModel.name
               userModel.pinYin = tool.py(contactModel.linkName?contactModel.linkName:contactModel.name)
               userModel.mobile = contactModel.linkMobile
               userModel.buId = contactModel.id
               userModel.buName = contactModel.name
               userModel.ctime = tool.getTime()
               await userModel.save()
               return ctx.suc('登录成功', userModel)
           }
           else if(num === 1) {
               //登录
               let userModel = await db.models['admin'].findOne({
                   where: {
                       username: mobile
                   }
               })
               if(userModel.tenantId !== contactModel.tenantId) {
                   return ctx.err('用户与终端所属经销商不匹配')
               }
               let tenant = await db.models['tenant'].findOne({
                   where:{
                       id: userModel.tenantId
                   }
               })
               let ret = userModel.toJSON()
               ret.tenantName = tenant.name
               ret.buName = contactModel.name
               return ctx.suc('登录成功', ret)
           }
           else {
               return ctx.err('此手机包含多个用户，禁止登录')
           }
       }
       else {
           return ctx.err('此手机包含多个终端')
       }
   }
   catch (e) {
       return ctx.err(e)
   }
}
const exeCurl1 = (command) => {
    return new Promise(async (resolve) => {
        exec(command,  (error, stdout) => {
            let obj = JSON.parse(stdout)
            if(obj.error) {
                resolve({stat: false, msg: obj.error, data: ''})
            }
            if (error !== null) {
                resolve({stat: false, msg: '验证失败', data: ''})
            }
            if (obj.msg === 'ok') {
                resolve({stat: true, msg: ''})
            } else {
                resolve({stat: false, msg: '验证失败'})
            }
        })
    })
}

module.exports = router;